//
//  News.m
//  News
//
//  Created by Heaven on 15/7/23.
//  Copyright (c) 2015年 Heaven. All rights reserved.
//

#import "News.h"
#import "NetworkTools.h"

@implementation News

+ (void)newsList:(NSString *)urlString finished:(void (^)(NSArray *))finished {

    NSAssert(finished, @"必须传入回调");
   
    [[NetworkTools sharedManager] GET:urlString parameters:nil success:^(NSURLSessionDataTask *task, NSDictionary *responseObject) {
        
        // 1. 取出字典第一个 key 对应的数组
        //NSArray *array = responseObject[[responseObject keyEnumerator].nextObject];
        NSArray *array = responseObject[responseObject.keyEnumerator.nextObject];
        // 2. 字典转模型
        NSMutableArray *arrayM = [NSMutableArray arrayWithCapacity:array.count];
        
        [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            [arrayM addObject:[self newsWithDict:obj]];
        }];

        finished(array.copy);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@", error);
    }];
    
   }

+ (instancetype)newsWithDict:(NSDictionary *)dict {
    id obj = [[self alloc] init];
    
    NSArray *properties = [self properties];
    
    // 遍历属性数组
    for (NSString *key in properties) {
        // 判断字典中是否包含这个key
        if (dict[key] != nil) {
            // 使用 KVC 设置数值
            [obj setValue:dict[key] forKeyPath:key];
        }
    }
    
    return obj;
}

+ (NSArray *)properties {
    return @[@"title", @"digest", @"replyCount", @"imgsrc", @"haha"];
}

- (NSString *)description {
    
    NSArray *properties = [News properties];
    NSDictionary *dict = [self dictionaryWithValuesForKeys:properties];
    
    return [NSString stringWithFormat:@"<%@: %p> %@", self.class, self, dict];
}


@end
